# -*- coding: utf-8 -*-
import gitee_package
import log_package
import ini_package
import pandas_package
from playwright_package import os_package
from gitee_package import re
from playwright_package import time_package
import playwright_package
import excel_package

# 数据清洗
def clean_data(file_path):
    """
    清洗数据
    :param ex:excel对象
    :return:
    """
    ex = excel_package.Excel_Option(file_path)
    ex.open_file()
    try:
        for sheet in ex.list_sheets():
            '''删除所有格式'''
            ex.clear_region_format(sheet)

            '''文本居中'''
            ex.modify_region_alignment(sheet, horizontal="center", vertical="center")

            '''删除None列'''
            while True:
                k = ex.get_sheet_headers(sheet)
                # print(k)
                if None in k:

                    # print(sheet)
                    ex.delete_column(sheet, k.index(None) + 1)
                else:
                    break

            '''删除None行'''
            # 配置行
            k = ex.get_column_values(sheet, "A")
            # 如果第一列数据是有行是None就要删除这一行
            while True:
                k = ex.get_column_values(sheet, "A")
                if None in k:
                    # print(k)
                    ex.delete_row(sheet, k.index(None) + 1)
                    # print(sheet)
                else:
                    break

            '''重置索引'''
            rows = ex.get_sheet_max_rows(sheet)
            p = 1
            for i in range(2, rows + 1):
                ex.modify_cell_value(sheet, i, 1, p)
                p += 1
        ex.save_file()
        ex.close_file()
        return True
    except Exception as e:
        ex.close_file()
        return False

# 获取gitee数据
def get_gitee_data():
    global ini_opt, ini_opt_school, ini_opt_header, file_name, is_add_nj, meta_file_name_url, meta_file_name
    try:
        # 连接gitee获取基本数据
        gitee_opt = gitee_package.Gitee_Option('https://gitee.com/zl_b/file_config.git',
                                               "06fbfe091fc755b51084d86966a14cc6")
        main_repo_data = gitee_opt.list_all_files_and_folders('金牛区相关信息')

        # 获取数据
        url = main_repo_data.get("重要配置.ini")
        if url:
            da = gitee_opt.get_gitee_repo_file(url)
            if da:
                ini_opt.read_ini_string(da)
                log_opt.write_success(f'成功获取gitee数据，【重要配置.ini】信息成功！')
                url_2 = main_repo_data.get("学校配置.ini")
                if url_2:
                    da = gitee_opt.get_gitee_repo_file(url_2)
                    if da:
                        ini_opt_school.read_ini_string(da)
                        log_opt.write_success(f'成功获取gitee数据，【学校配置.ini】信息成功！')
                        url_3 = main_repo_data.get("名单header配置.ini")
                        if url_3:
                            da = gitee_opt.get_gitee_repo_file(url_3)
                            if da:
                                ini_opt_header.read_ini_string(da)
                                log_opt.write_success(f'成功获取gitee数据，【名单header配置.ini】信息成功！')
                                file_name = f"{ini_opt.get_section_option('新名单配置', 'file_name_year')}{ini_opt.get_section_option('新名单配置', 'jj')}名单.xlsx"
                                is_add_nj = bool(int(ini_opt.get_section_option('新名单配置', 'is_add_nj')))
                                meta_file_name = ini_opt.get_section_option('main_xlsx', 'name')
                                meta_file_name_url = ini_opt.get_section_option('main_xlsx', 'url')
                                return True
                            else:
                                raise Exception('获取【名单header配置.ini】信息失败！')
                        else:
                            raise Exception('未找到-【名单header配置.ini】！')
                return True
            else:
                raise Exception('获取【重要配置.ini】信息失败！')
        else:
            raise Exception('未找到-【重要配置.ini】！')
    except Exception as e:
        log_opt.write_error(f'获取gitee出现错误{e}')
        return False

# 分割学校名称
def extract_school_name(item):
    if "竞赛" in item:
        match = re.search(r'(\w+)竞赛', item)
        if match:
            return match.group(1)
        else:
            return None

    elif "普" in item:
        match = re.search(r'(\w+)普', item)
        if match:
            return match.group(1)
        else:
            return None
    else:
        return None

# 分割年级
def extract_text_by_nodes(text):
    patterns = [r'(.*?)(普|竞赛)(.*)', r'(.*)(普|竞赛)$']
    for pattern in patterns:
        match = re.search(pattern, text)
        if match:
            return match.group(1), match.group(2), match.group(3)
    return "", "", ""

# 处理源文件
def process_the_file(file_path):
    try:
        log_opt.write_info(f'正在清洗【{file_path}】数据...')
        if not clean_data(file_path):
            log_opt.write_error(f'清洗【{file_path}】数据失败！')
            raise Exception(f'清洗【{file_path}】数据失败！')
        log_opt.write_success(f'清洗【{file_path}】数据成功！')
        ex_main = excel_package.Excel_Option(file_path)
        ex_main.open_file()
        sheet_names = ex_main.list_sheets()
        # print(ex_main.list_sheets())
        if '竞赛模板' in sheet_names:
            sheet_names.remove('竞赛模板')
        if '普模板' in sheet_names:
            sheet_names.remove('普模板')

        """
        先判断名单中每个表的表头是否一致
        """
        log_opt.write_info('核实各个sheet表头...')
        pj_sheet_is_false = []
        js_sheet_is_false = []

        for sheet in sheet_names:
            # print(sheet)
            # 学校全名
            full_name_of_the_school = extract_school_name(sheet)
            # print(full_name_of_the_school)
            for i in ini_opt_school.list_sections():
                for k in ini_opt_school.list_section_options(i):
                    if ini_opt_school.get_section_option(i, k) == full_name_of_the_school:
                        full_name_of_the_school = i
                        break  # 立即退出内层循环
                else:
                    # 若内层循环未被break，继续执行外层循环
                    continue
                # 若内层循环被break，也跳出外层循环
                break
            # print(full_name_of_the_school)

            sheet_split_data = extract_text_by_nodes(sheet)
            # 判断是否班级类型
            # headers = []
            headers = ex_main.get_sheet_headers(sheet)
            # if sheet_split_data[1] == '普':
            #     headers = ex_main.get_sheet_headers(sheet)
            # else:
            #     for i in ini_opt_header.list_section_options('竞赛'):
            #         if eval(ini_opt_header.get_section_option('竞赛', i)):
            #             headers.append(i)

            # print(headers)
            if sheet_split_data[1] == '普':
                bz_headers = ex_main.get_sheet_headers(ini_opt.get_section_option('判断标准', 'pj_name'))
            else:
                bz_headers = ex_main.get_sheet_headers(ini_opt.get_section_option('判断标准', 'js_name'))
            # print(bz_headers)
            if headers[:headers.index('考勤数据')+1] != bz_headers[:bz_headers.index('考勤数据')+1]:
                if sheet_split_data[1] == '普':
                    pj_sheet_is_false.append(sheet)
                else:
                    js_sheet_is_false.append(sheet)
            # print(headers[:headers.index('考勤数据')+1])
            # print(bz_headers[:bz_headers.index('考勤数据')+1])

        is_continue = True
        if pj_sheet_is_false != []:
            is_continue = False
            log_opt.write_info(f'{"*"*30}普教{"*"*30}')
            for s in pj_sheet_is_false:
                log_opt.write_warning(f'普教中的【{s}】表头不正确，请核实！')
            log_opt.write_info(f'{"*"*70}')

        if js_sheet_is_false != []:
            is_continue = False
            log_opt.write_info(f'{"*" * 30}竞赛{"*" * 30}')
            for s in js_sheet_is_false:
                log_opt.write_warning(f'竞赛中的【{s}】表头不正确，请核实！')
            log_opt.write_info(f'{"*" * 70}')
        if not is_continue:
            return False
        log_opt.write_success('各个sheet表头核实成功！')
        # ex_main.save_file()
        return True
    except Exception as e:
        log_opt.write_error(f'处理源文件出现错误{e}')
        return False

if __name__ == '__main__':
    print('''请输入目标文件(xlsx)路径：''')
    user_file_path = str(input())
    # 初始化
    time_opt = time_package.Time_Option()
    time_opt.start_timing()
    log_opt = log_package.Logging_Option()
    log_opt.write_info('正在初始化...')
    ini_opt = ini_package.Config_Option()
    ini_opt_school = ini_package.Config_Option()
    ini_opt_header = ini_package.Config_Option()
    os_opt = os_package.Os_Option()
    os_opt.make_file_folder('file')
    os_opt.make_file_folder('log')
    log_opt.write_success('初始化成功！')

    file_name = ""
    is_add_nj = False
    meta_file_name = ''
    meta_file_name_url = ''

    try:
        log_opt.write_info('正在获取gitee数据...')
        # 获取gitee数据
        if get_gitee_data():
            log_opt.write_success('获取gitee数据成功！')
            # print(file_name)
            if process_the_file(user_file_path):
                log_opt.write_success(f'处理【file/{meta_file_name}】数据完毕！')
            else:
                raise Exception(f'处理【{user_file_path}】数据失败！')
        else:
            raise Exception('获取gitee数据失败!')
    except Exception as e:
        log_opt.write_error(f'程序异常：{e}')
    finally:
        log_opt.write_info(f'程序用时：{time_opt.end_timing()}')
        time_opt.timesleep(3)
